package com.glory.hikvisionmobile.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.adapter.BindCarrierListAdapter;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.base.Constant;
import com.glory.hikvisionmobile.bean.TrackIn.XPdaDieboundMappingBean;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.bean.TrackIn.BoundCarrierBean;
import com.glory.hikvisionmobile.utils.DialogUtils;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class Work_BindCarrierActivity extends BaseActivity {

    @BindView(R.id.etCarrier)
    FreeUI_ClearEditText etCarrier;
    @BindView(R.id.rvBindCarrierList)
    RecyclerView rvBindCarrierList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.list_titleLayout)
    LinearLayout listTitleLayout;
    @BindView(R.id.tvReplay)
    TextView tvReplay;
    private BindCarrierListAdapter bindCarrierListAdapter;
    private String lotID;
    private List<XPdaDieboundMappingBean> xPdaDieboundMappingBeans;
    private String tubeShellSpec;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_bind_carrier;
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        lotID = bundle.getString("lotID");
        rvBindCarrierList.setLayoutManager(new LinearLayoutManager(Work_BindCarrierActivity.this));
        rvBindCarrierList.setItemAnimator(new DefaultItemAnimator());
        rvBindCarrierList.addItemDecoration(new DividerItemDecoration(Work_BindCarrierActivity.this, 1));
        bindCarrierListAdapter = new BindCarrierListAdapter(null);
        bindCarrierListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        bindCarrierListAdapter.isFirstOnly(true);
        rvBindCarrierList.setAdapter(bindCarrierListAdapter);

        initEdit(etCarrier, s -> getCarrierList(s));
    }


    private void getCarrierList(String carrierId) {
        JsonObject map = new JsonObject();
        map.addProperty("carrierId",carrierId);
        map.addProperty("actionType","LOAD");
        map.addProperty("lotId",lotID);
        NetUtils.requestDara("HIK.PdaBoundCarrier",this,map,new FreeUI_DialogEntityCallBack<BaseResponseBean<BoundCarrierBean>>(
                new TypeToken<BaseResponseBean<BoundCarrierBean>>() {
                }.getType(), getSupportFragmentManager(), this){

            @Override
            public void onSuccess(Response<BaseResponseBean<BoundCarrierBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())) {
                    BoundCarrierBean boundCarrierBean = response.body().getBody();
                    xPdaDieboundMappingBeans = boundCarrierBean.getxPdaDieBoundMappings();
                    tubeShellSpec = boundCarrierBean.getTubeShellSpec();
                    bindCarrierListAdapter.setNewData(xPdaDieboundMappingBeans);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<BoundCarrierBean>> response) {
                super.onError(response);
                loadError(response.getException(),"HIK.PdaBoundCarrier");
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("载具绑定");
        return new FreeUI_AddViewEntity("header", llMain);
    }


    @OnClick(R.id.tvReplay)
    public void onViewClicked() {
        initPermission("Submit", this, new ActionControlListener() {
            @Override
            public void onControlChangeListener() {

                if (editIsEmpty(etCarrier,"载具号不能为空")) {
                    if (compareTubeShellID(bindCarrierListAdapter.getData()).equals("Y")){
                        submit();
                    }
                }
            }
        });

    }

    private String compareTubeShellID(List<XPdaDieboundMappingBean> data) {
        String compare = "N";
        List<String> tubeID = new ArrayList<>();

        Iterator<XPdaDieboundMappingBean> iterator = data.iterator();
        while (iterator.hasNext()){
            String tubeShellId = iterator.next().getTubeShellId();
            if (tubeShellId.length() == 0) {
                if (!iterator.hasNext()){ //管壳ID为空，不进行筛选，遍历完成后，赋值
                    compare = "Y";
                }
                continue;
            }

            if (tubeShellSpec.length() == 0){ //没有筛选条件，只判断重复
                if (tubeID.contains(tubeShellId)){
                    showConfirmDialog(tubeShellId + "管壳元素重复");
                    break;
                }else {
                    tubeID.add(tubeShellId);
                    if (!iterator.hasNext()){
                        compare = "Y";
                    }
                }
            }else {//判断管壳前缀和重复元素
                if (tubeShellId.length() < tubeShellSpec.length()){
                    showConfirmDialog("管壳前缀不匹配");
                    break;
                }else {
                    String substring = tubeShellId.substring(0, tubeShellSpec.length());
                    if (!substring.equals(tubeShellSpec)) {
                        showConfirmDialog("管壳前缀不匹配");
                        break;
                    }else {
                        if (tubeID.contains(tubeShellId)){
                            showConfirmDialog(tubeShellId + "管壳元素重复");
                            break;
                        }else {
                            tubeID.add(tubeShellId);
                            if (!iterator.hasNext()){
                                compare = "Y";
                            }
                        }
                    }
                }
            }
        }

        return compare;
    }

    private void submit() {
        DialogUtils.showLoginDialog(this, Constant.CURRENT_USER, new DialogUtils.signCallback() {
            @Override
            public void onSignSuccess() {
                JsonObject map = new JsonObject();
                JsonObject json = new JsonObject();
                json.add("XPdaDieboundMapping",new JsonParser().parse(new Gson().toJson(bindCarrierListAdapter.getData())).getAsJsonArray());
                map.addProperty("carrierId",etCarrier.getText().toString().trim());
                map.addProperty("actionType","SAVE");
                map.add("xPdaDieboundMappings",json);
                NetUtils.requestDara("HIK.PdaBoundCarrier",this,map,new FreeUI_DialogEntityCallBack<BaseResponseBean<BoundCarrierBean>>(
                        new TypeToken<BaseResponseBean<BoundCarrierBean>>() {
                        }.getType(), getSupportFragmentManager(), this){

                    @Override
                    public void onSuccess(Response<BaseResponseBean<BoundCarrierBean>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())) {
                            showConfirmDialog(Work_BindCarrierActivity.this,"载具绑定成功");
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<BoundCarrierBean>> response) {
                        super.onError(response);
                        loadError(response.getException(),"HIK.PdaBoundCarrier");
                    }
                });
            }
        },getSupportFragmentManager());
    }

}
